package com.wsq.helper;

import java.io.IOException;
import java.util.Locale;

import android.app.Activity;
import android.app.KeyguardManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.WindowManager;
import android.widget.Toast;

import com.wsq.calculate.R;

/**
 * utility class for android
 * 
 * @author yardi
 * 
 */
public class ViewHelper {
    private final String TAG = "ViewHelper";
    public static ViewHelper sHelper;

    public static ViewHelper instance() {
	if (sHelper == null) {
	    sHelper = new ViewHelper();
	}
	return sHelper;
    }

    public ViewHelper() {
	super();
    }

    private ProgressDialog myDialog;

    public void showDialog(Context context) {
	myDialog = new ProgressDialog(context);
	myDialog.setCanceledOnTouchOutside(false);
	myDialog.setCancelable(false);
	myDialog.setIndeterminate(false);
	myDialog.setMessage("");
	myDialog.show();
    }

    public void toastNetwork(Context context) {
	Toast.makeText(context,"", Toast.LENGTH_SHORT).show();
    }

    public void dissmissDialog(Activity activity) {
	if (myDialog != null && myDialog.isShowing() && !activity.isFinishing()) {
	    myDialog.dismiss();
	    myDialog = null;
	}
    }

    /**
     * get the width of screen
     * 
     * @param mContext
     * @return
     */
    public int getScreenWidth(Context activity) {
	Display display = ((WindowManager) activity
		.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
	return display.getWidth();
    }

    /**
     * get the height of screen
     * 
     * @param mContext
     * @return
     */
    public int getScreenHeight(Context activity) {
	Display display = ((WindowManager) activity
		.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
	return display.getHeight();
    }

    /**
     * translate dip to pixel
     * 
     * @param context
     * @param dipValue
     * @return
     */
    public int dip2px(Context context, float dipValue) {
	final float scale = context.getResources().getDisplayMetrics().density;
	return (int) (dipValue * scale + 0.5f);
    }

    public int px2dip(Context context, float pxvalue) {
	final float scale = context.getResources().getDisplayMetrics().density;
	return (int) ((pxvalue - 0.5f) / scale);
    }

    public int getHeightWithPixel(Context context, int count, float minHeight) {
	minHeight = dip2px(context, minHeight);
	return (int) (minHeight * count);
    }

    /**
     * set margins of the widget in the code
     * 
     * @param widget
     * @param left
     *            left margin
     * @param top
     *            top margin
     * @param right
     *            right margin
     * @param bottom
     *            bottom margin
     */
    public void setMargins(View widget, int left, int top, int right, int bottom) {
	MarginLayoutParams layout = (MarginLayoutParams) widget
		.getLayoutParams();
	layout.setMargins(left, top, right, bottom);
    }

    /**
     * update the language of the screen ,and retained for later using
     * 
     * @param context
     */
    public void updateLanguage(Context context) {
	Locale locale = getLocaleFromPreference();
	Resources resources = context.getResources();
	Configuration cfg = resources.getConfiguration();
	cfg.locale = locale;
	resources.updateConfiguration(cfg, null);
    }

    /**
     * return a Locale instance from preference
     * 
     * @return
     */
    private Locale getLocaleFromPreference() {
	return Locale.SIMPLIFIED_CHINESE;
    }

    /**
     * check the keyguard
     */

    public boolean checkKeyguard(Activity activity) {
	KeyguardManager key_guard = (KeyguardManager) activity
		.getSystemService(Context.KEYGUARD_SERVICE);
	boolean isInputRestricted = key_guard.inKeyguardRestrictedInputMode();
	return isInputRestricted;
    }

    public String getVersionCode(Context context) {
	try {
	    PackageInfo pinfo = context.getPackageManager()
		    .getPackageInfo(context.getPackageName(),
			    PackageManager.GET_CONFIGURATIONS);
	    String versionCode = pinfo.versionName;
	    return versionCode;
	} catch (NameNotFoundException e) {
	    return null;
	}
    }

    private static WifiManager mWifiManager;

    public boolean isNetworkAvailable(Context context) {
	ConnectivityManager connectivity = (ConnectivityManager) context
		.getSystemService(Context.CONNECTIVITY_SERVICE);
	if (connectivity == null) {
	    return false;
	} else {
	    NetworkInfo[] info = connectivity.getAllNetworkInfo();
	    if (info != null) {
		for (int i = 0; i < info.length; i++) {
		    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
			return true;
		    }
		}
	    }
	}
	return false;
    }

    public boolean isWifiAvailable(Context context) {
	if (mWifiManager == null) {
	    mWifiManager = (WifiManager) context
		    .getSystemService(Context.WIFI_SERVICE);
	}
	WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
	int ipAddress = wifiInfo == null ? 0 : wifiInfo.getIpAddress();
	if (mWifiManager.isWifiEnabled() && ipAddress != 0) {
	    return true;
	} else {
	    return false;
	}
    }

    // <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
    // />
    // <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    public boolean isAvaible(Context context) {
	return isNetworkAvailable(context) || isWifiAvailable(context);
    }

    public Bitmap getCollectBitmap(String filepath, Context context) {
	Bitmap bitmap = null;
	try {
	    ExifInterface exifInterface = new ExifInterface(filepath);
	    int result = exifInterface.getAttributeInt(
		    ExifInterface.TAG_ORIENTATION,
		    ExifInterface.ORIENTATION_UNDEFINED);
	    int rotate = 0;
	    switch (result) {
	    case ExifInterface.ORIENTATION_ROTATE_90:
		rotate = 90;
		break;
	    case ExifInterface.ORIENTATION_ROTATE_180:
		rotate = 180;
		break;
	    case ExifInterface.ORIENTATION_ROTATE_270:
		rotate = 270;
		break;
	    default:
		break;
	    }
	    BitmapFactory.Options options = new BitmapFactory.Options();
	    options.inPreferredConfig = Bitmap.Config.RGB_565;
	    options.inJustDecodeBounds = true;
	    BitmapFactory.decodeFile(filepath, options);
	    if (options.outWidth < 0 || options.outHeight < 0) {
		return null;
	    }

	    int mScreenWidth = getScreenWidth(context);
	    int mScreenHeight = getScreenHeight(context);

	    int sampleSize = calculateInSampleSize(options, mScreenWidth,
		    mScreenHeight);
	    
	    options.inSampleSize=sampleSize;
	    options.inJustDecodeBounds = false;
	    bitmap = BitmapFactory.decodeFile(filepath, options);
	    if (rotate > 0) {
		Matrix matrix = new Matrix();
		matrix.setRotate(rotate);
		Bitmap rotateBitmap = Bitmap.createBitmap(bitmap, 0, 0,
			options.outWidth, options.outHeight, matrix, true);
		if (rotateBitmap != null) {
		    bitmap.recycle();
		    bitmap = rotateBitmap;
		}
	    }
	    return bitmap;
	} catch (IOException e) {
	    return bitmap;
	}
    }

    private static int calculateInSampleSize(BitmapFactory.Options options,
	    int reqWidth, int reqHeight) {
	// Raw height and width of image
	final int height = options.outHeight;
	final int width = options.outWidth;
	int inSampleSize = 1;

	if (height > reqHeight || width > reqWidth) {
	    if (width > height) {
		inSampleSize = Math.round((float) height / (float) reqHeight);
	    } else {
		inSampleSize = Math.round((float) width / (float) reqWidth);
	    }

	    // This offers some additional logic in case the image has a strange
	    // aspect ratio. For example, a panorama may have a much larger
	    // width than height. In these cases the total pixels might still
	    // end up being too large to fit comfortably in memory, so we should
	    // be more aggressive with sample down the image (=larger
	    // inSampleSize).

	    final float totalPixels = width * height;

	    // Anything more than 2x the requested pixels we'll sample down
	    // further.
	    final float totalReqPixelsCap = reqWidth * reqHeight * 2;

	    while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
		inSampleSize++;
	    }
	}
	return inSampleSize;
    }

}